import { combineReducers } from 'redux';
import * as actionTypes from '../actionTypes';

// 对于产品的操作
// 当增加或者减少时，只是改变的是库存量
function products(state, action) {
  switch (action.type) {
    case actionTypes.ADD_TO_CART:
      return {
        ...state,
        inventory: state.inventory - 1
      }
    case actionTypes.REMOVE_FROM_CART:
      return {
        ...state,
        inventory: state.inventory + 1,
      }  
    default:
      return state
  }
}

// 获取产品信息，并将产品id作为key, 产品信息作为value
function byId(state = {}, action) {
  switch (action.type) {
    case actionTypes.RECEIVE_PRODUCTS:
      return {
        ...state,
        // 骚操作，我也是抄来的
        ...action.products.reduce((obj, product) => {
          obj[product.id] = product;
          return obj
        }, {})
      }
    default:
      const { productId } = action;
      if (productId) {
        return {
          ...state,
          [productId]: products(state[productId], action)
        }
      }
      return state
  }
}

// 根据传入的产品id， 获取到产品信息
function visibleIds(state = [], action) {
  switch (action.type) {
    case actionTypes.RECEIVE_PRODUCTS:
      return action.products.map(product => product.id)
    default:
      return state
  }
}

// 根据当前传传入的id 获取到产品信息
export function getProducts(state, id) {
  return state.byId[id]
}

export function getVisibleProducts(state) {
  // state = {byId: {}, visibleIds: []}
  return state.visibleIds.map(id => getProducts(state, id))
}

export default combineReducers({
  byId,
  visibleIds
})